package com.fundodoo.sfe.admin.controller;

import java.util.Locale;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.support.RequestContextUtils;

import com.fundodoo.sfe.admin.dao.UserRepository;
import com.fundodoo.sfe.common.annotation.Log;
import com.fundodoo.sfe.common.controller.BaseController;
import com.fundodoo.sfe.common.po.ResponseBo;
import com.fundodoo.sfe.common.po.SfeInfo;
import com.fundodoo.sfe.common.utils.fundodooCode.Captcha;
import com.fundodoo.sfe.common.utils.fundodooCode.GifCaptcha;
import com.fundodoo.sfe.domain.User;

@Controller
public class LoginController extends BaseController {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    private static final String CODE_KEY = "_code";
    
    @Autowired
    private SfeInfo sfeInfo;
    
    @Autowired
    private UserRepository userRepository;
    
    @GetMapping("/login")
    public String login(Model model) {
    	model.addAttribute("version",sfeInfo.getAppInfo().getVersion());
        return "login";
    }
    
    @Log("登录系统 ")
    @PostMapping("/login")
    @ResponseBody
    public ResponseBo login(String username, String password, String code, Boolean rememberMe,HttpServletResponse response) {
        if (!StringUtils.isNotBlank(code)) {
            return ResponseBo.warn("login.verification.code.blank");
        }
        Session session = super.getSession();
        String sessionCode = (String) session.getAttribute(CODE_KEY);
        if (!code.equalsIgnoreCase(sessionCode)) {
            return ResponseBo.warn("login.verification.code.error");
        }
        
        // 密码 MD5 加密
        password = DigestUtils.md5Hex(password);
        UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
        try {
            Subject subject = getSubject();
            if (subject != null)
                subject.logout();
            super.login(token);
            	return ResponseBo.ok();
            
        } catch (UnknownAccountException | IncorrectCredentialsException | LockedAccountException e) {
            return ResponseBo.error(e.getMessage());
        } catch (AuthenticationException e) {
            return ResponseBo.error("login.authentication.fail");
        }
    }

    @GetMapping(value = "gifCode")
    public void getGifCode(HttpServletResponse response, HttpServletRequest request) {
        try {
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setContentType("image/gif");

            Captcha captcha = new GifCaptcha(
                    sfeInfo.getValidateCodeInfo().getWidth(),
                    sfeInfo.getValidateCodeInfo().getHeight(),
                    sfeInfo.getValidateCodeInfo().getLength());
            HttpSession session = request.getSession(true);
            captcha.out(response.getOutputStream());
            session.removeAttribute(CODE_KEY);
            session.setAttribute(CODE_KEY, captcha.text().toLowerCase());
        } catch (Exception e) {
            log.error("图形验证码生成失败", e);
        }
    }

    @RequestMapping("/")
    public String redirectIndex() {
        return "redirect:/index";
    }
    
    @Log("退出系统 ")
    @GetMapping("/to_logout")
    public String logout() {
		//add by jm.hong 20190117 delete cookie  when logout---start---
    	ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if(null != requestAttributes) {
        	Subject subject = SecurityUtils.getSubject();
        	String sessionId = subject.getSession().getId().toString();
        	HttpServletRequest request = requestAttributes.getRequest();
        	HttpServletResponse reponse = requestAttributes.getResponse();
    		Cookie[] cookies = request.getCookies();
    		if(cookies != null){
                for(Cookie cookie : cookies){
                    if(cookie.getName().equals(sessionId)){
                        //更新cookie
//                    	log.info("退出删除cookie开始......");
                    	cookie.setPath("/");
                    	cookie.setMaxAge(0);
                    	reponse.addCookie(cookie);
//                    	log.info("退出删除cookie结束......");
                    }
                }
            }
        }
    	//add by jm.hong 20190117 delete cookie when logout---end---
        return "redirect:/logout";
    }

    @GetMapping("/403")
    public String forbid() {
        return "403";
    }

    @RequestMapping("/index")
    public String index(Model model) {
        // 登录成后，即可通过 Subject 获取登录的用户信息
        User user = super.getCurrentUser();
        model.addAttribute("sessionId",super.getSession().getId().toString());
        model.addAttribute("user", user);
        
        model.addAttribute("version",sfeInfo.getAppInfo().getVersion());
        return "index";
    }
    
    @Log("设置国际化 ")
    @GetMapping("/language")
    public ModelAndView  language(HttpServletRequest request, HttpServletResponse response, String language){
        LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
        language=language.toLowerCase();
        log.info("language:"+language);
        if(language==null||language.equals("")){
            return new ModelAndView("login");
        }else{
            if(language.equals("zh_cn")){
                localeResolver.setLocale(request, response, Locale.CHINA);
            }else if(language.equals("en")){
                localeResolver.setLocale(request, response, Locale.US);
            }else{
                localeResolver.setLocale(request, response, Locale.CHINA );
            }
        }
        return new ModelAndView("redirect:/index");
    }
}
